#include <iostream>
#include <sstream>
#include <fstream>
#include "../Headers/log.h"
#include "../Headers/config.h"

// Constructor
TOB::Config::Config(std::string path) {
  this->path = path;
  read();
}


// Constructor (wide)
TOB::Config::Config(std::wstring path) {
  this->path = UTF8Encoding::convert(path);
  read();
}


// Destructor
TOB::Config::~Config() {
}


// Read file
TOB::Config &TOB::Config::read() {
  std::string line;
  std::ifstream handle(path.c_str());
  if(!handle.is_open()) return *this;

  while(handle.good()) {
    getline(handle, line);
    if(!line.size() || line[0] == '#') continue;
    size_t delimPos = line.find("=");
    std::string key = line.substr(0, delimPos); 
    if(!key.size()) continue;
#ifdef ADVANCED_LANG
    std::string substr = line.substr(delimPos+1);
    map[key] = UTF8Encoding::convert(substr);
#else
    map[key] = line.substr(delimPos+1);
#endif
  }

  handle.close();
  Log::event("Config '" + path + "' has been read");
  return *this;
}


// Get string value
String &TOB::Config::stringValue(std::string key) {
  return map[key];
}


// Get int value
int32 TOB::Config::intValue(std::string key) {
  StringStream stream(map[key]);
  int32 res;
  stream >> res;
  return res;
}

// Get float value
Float TOB::Config::floatValue(std::string key) {
  StringStream stream(map[key]);
  Float res;
  stream >> res;
  return res;
}

// Fast access
String &TOB::Config::operator[](std::string key) {
  return map[key];
}
